/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.kyiv.yellow.sociallibrary.social.web;

import com.nc.kyiv.yellow.sociallibrary.beans.user.UserBeanLocal;
import com.nc.kyiv.yellow.sociallibrary.beans.user.UserBeanLocalHome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author My
 */
public class Vk extends HttpServlet {

    HttpURLConnection conn;
    BufferedReader rd;
    String access_token = "";
    String personalData = "";
    String clientId = "4039026";
    String clientSecrt = "wotjPCDTdKMI0TyJr5Fa";
    String redirectUri = "http://localhost:8080/SocialLibrary-web/Vk";
    String toRedirect = "http://localhost:8080/SocialLibrary-web/";
    String responseType = "code";

    public void init() throws ServletException {
        super.init();
        userBean = lookupUserBeanLocal();  // not here
    }
    private UserBeanLocal userBean = null;

    private Map parseJSON(String json) {
        String[] lines = json.split("\r\n");
        Map<String, String> myMap = new HashMap<>();

        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            String[] pair = line.split(":");

            if (pair.length >= 2) {
                String key = clearString(pair[0]);
                String value = clearString(pair[1]);
                if (value != "{") {
                    myMap.put(key, value);
                }
            }
        }
        return myMap;
    }

    private String clearString(String str) {
        str = str.trim();
        int ind0 = str.indexOf("\"");
        int ind1 = str.lastIndexOf("\"");
        if (ind0 != -1 && ind1 != -1) {
            str = str.substring(ind0 + 1, ind1);
        } else if (str.toCharArray()[str.length() - 1] == ',') {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    public String getStringFromHTML(URL url) throws IOException {
        String result = "";
        String line;
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        return result;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        if (request.getParameter("code") == null) {
        }


        if (request.getParameter("code") != null) {

            URL urlForAccressToken = new URL("https://oauth.vk.com/access_token?client_id=" + clientId + "&"
                    + "client_secret=" + clientSecrt + "&code=" + request.getParameter("code")
                    + "&redirect_uri=" + redirectUri);
            access_token = getStringFromHTML(urlForAccressToken).split(":")[1].split(",")[0];
            access_token = access_token.substring(1, access_token.length() - 1);

            URL urlForPersonalData = new URL("https://api.vk.com/method/users.get?fields=sex,bdate&access_token=" + access_token);
            personalData = getStringFromHTML(urlForPersonalData);


            // PARSE
            Map pdMap = parseJSON(personalData);
            String check = personalData;
            check = check.replace("{", "{\r\n");
            check = check.replace(",", ",\r\n");
            check = check.replace("[", "[\r\n");
            pdMap = parseJSON(check);
            // Load to DB

            Map paramsRegistration = new HashMap<String, String>();
            paramsRegistration.put("login", pdMap.get("uid"));
            paramsRegistration.put("pass", "111");
            paramsRegistration.put("last_name", pdMap.get("last_name"));
            paramsRegistration.put("first_name", pdMap.get("first_name"));
            paramsRegistration.put("email", "testVk@vk.vk");
            userBean.registerUserWithSocNetwork(paramsRegistration);
            
            /*create cookies*/
            Cookie cookieLog2 = new Cookie("sllogin",(String) pdMap.get("uid"));
            cookieLog2.setMaxAge(14 * 24 * 60 * 60);
            Cookie cookiePas2 = new Cookie("slpass", "111");
            cookiePas2.setMaxAge(14 * 24 * 60 * 60);

            response.addCookie(cookieLog2);
            response.addCookie(cookiePas2);
            
            response.sendRedirect(toRedirect);
        }


        try {
            /* TODO output your page here. You may use following sample code. */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private UserBeanLocal lookupUserBeanLocal() {
        try {
            Context c = new InitialContext();
            UserBeanLocalHome rv = (UserBeanLocalHome) c.lookup("java:comp/env/UserBean");
            return rv.create();
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        } catch (CreateException ce) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ce);
            throw new RuntimeException(ce);
        }
    }
}